import { defineStore } from 'pinia'
import { getInfo, login, loginByCode, logout } from '@/api/login'
import { getToken, removeToken, setToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import type { Dept } from '@/types/user'

interface UserState {
  token: string
  id?: number
  name: string
  avatar: string
  sex?: string
  roles: string[]
  nickName: string
  permissions: string[]
  dept?: Dept
  passwordStatus?: string
}

const useUserStore = defineStore(
  'user',
  {
    state: (): UserState => ({
      token: getToken(),
      name: '',
      nickName: '',
      avatar: '',
      sex: '',
      roles: [],
      permissions: [],
    }),
    actions: {
      // 登录
      login(userInfo: { username: string; password: string; type: 't1' } | { tel: string; code: string; type: 't2' }) {
        const { type } = userInfo
        if (type === 't1') {
          return new Promise<void>((resolve, reject) => {
            const { username, password } = userInfo
            login(username, password).then((res) => {
              setToken(res.token)
              this.token = res.token
              resolve()
            }).catch((error: any) => {
              reject(error)
            })
          })
        }
        else {
          return new Promise<void>((resolve, reject) => {
            const { tel, code } = userInfo
            loginByCode(tel, code).then((res) => {
              setToken(res.token)
              this.token = res.token
              resolve()
            }).catch((error: any) => {
              reject(error)
            })
          })
        }
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then((res) => {
            const user = res.user
            const avatar = (user.avatar === '' || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            }
            else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            this.name = user.userName
            this.nickName = user.nickName
            this.avatar = avatar
            this.sex = user.sex
            this.dept = user.dept
            this.passwordStatus = user.passwordStatus
            resolve(res)
          }).catch((error: any) => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise<void>((resolve, reject) => {
          logout().then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch((error: any) => {
            reject(error)
          })
        })
      },
    },
  },
)

export default useUserStore
